package masterpiece.util;

import java.util.*;
import java.io.*;
import java.sql.*;
import java.sql.Date;

/**
 * Tester program for the Utilities class.
 * @author Fredrik
 * @author oconnecp
 * @author Travis Towne
 * @author Brad Ballinger
 */
public class UtilitiesTester {
	
	/** The Utilities object used for testing. */
	static Utilities utilities;
	
	/** Standard input as a Scanner instance. */
	static Scanner in;
	
	/**
	 * @param args There are no console arguments for this application.
	 * @author Fredrik
	 * @author oconnecp
	 * @author Travis Towne
	 */
	public static void main(String[] args) {
		utilities = new Utilities();
		in 		  = new Scanner(System.in);
		
		boolean allDone = false;
		while(!allDone) {
			displayMainMenu();
			try {
				int choice = Integer.parseInt(in.nextLine());
				switch(choice) {
				case 1:
					openDB();
					break;
				case 2:
					openDBWithUsernameAndPassword();
					break;
				case 3:
					searchArchive();
					break;
				case 4:
					newArticle();
					break;
				case 5:
					editArticle();
					break;
				case 6:
					createUser();
					break;
				case 7:
					deletePicture();
					break;
				case 8:
					addNewPicture();
					break;
				case 9:
					allDone = true;
					break;
				case 10:
					callUpdateSection();
					break;
				default:
					System.out.println("Invalid choice.");
				}
			} catch (NumberFormatException e) {
				System.out.println("Not an integer.");
			}
		}
		
		System.out.println("Bye.");
	}
	
	/**
	 * Displays the main command menu.
	 * @author Fredrik
	 * @author oconnecp
	 * @author Travis Towne
	 */
	static void displayMainMenu() {
		System.out.print(
			"Enter an integer to choose:\n" +
			"  1. Open connection using default user name and password.\n" +
			"  2. Open connection.\n" +
			"  3. Search archive.\n" +
			"  4. Submit article.\n" +
			"  5. Update article.\n" +
			"  6. Create User.\n" +
			"  7. Delete Picture.\n" +
			"  8. Add Picture.\n" +
			"  9. Quit.\n" +
			"  10. Update Status, Rank Section for Article 1000.\n" +
			"> "
		);
	}
	
	/**
	 * Calls Utilities.openDB().
	 * @author Fredrik
	 */
	static void openDB() {
		try {
			utilities.openDB();
		} catch (SQLException e) {
			System.out.println(e);
		} catch (ClassNotFoundException e) {
			System.out.println(e);
		}
	}
	
	/**
	 * Prompts user for user name and password, then calls Utilities.openDB()
	 * with the values provided.
	 * @author Fredrik
	 */
	static void openDBWithUsernameAndPassword() {
		String username;
		String password;
		
		System.out.print("User name: ");
		username = in.nextLine();
		
		System.out.print("Password: ");
		password = in.nextLine();
		
		try {
			utilities.openDB(username, password);
		} catch (SQLException e) {
			System.out.println(e);
		} catch (ClassNotFoundException e) {
			System.out.println(e);
		}
	}

	/**
	 * This method prompts the user for all the information needed to 
	 * submit an article to the DB and passes it to utilities.
	 * 
	 * @author Travis Towne
	 */
	static void newArticle() {
		try {
			boolean stop = false;
		
			System.out.print("ePass: ");
			String ePass = in.nextLine();
		
			System.out.print("The following information is needed to submit an article:\n\n");
		
			System.out.print("Headline: ");
			String headline = in.next();
			headline += in.nextLine();
			
			System.out.print("Sub_Headline: ");
			String sub_headline = in.next();
			sub_headline += in.nextLine();
			
			java.sql.Date article_date = new java.sql.Date(System.currentTimeMillis());
		
			int tempChoice = 0;
			while(!stop) {
				System.out.print("Enter the number for the section:\n" +
								 "1) News\n" +
								 "2) Op-Ed\n" +
								 "3) LuteLife\n" +
								 "4) International\n" +
								 "5) Arts & Intertainment\n" +
								 "6) Sports\n" +
							 	 "---> ");
				try {
					tempChoice = in.nextInt();
					in.nextLine();
					if(tempChoice < 1 || tempChoice > 6)
						throw new IllegalArgumentException();
					stop = true;
				} catch(Exception e1) {
					System.out.println("Enter a number from 1-6.");
				}
			}
			String section = "";
			section += tempChoice;
			
			System.out.print("Body: ");
			String body = in.next();
			body += in.nextLine();
			
			System.out.print("Issue Date(YYYY-MM-DD): ");
			java.sql.Date issue = java.sql.Date.valueOf(in.nextLine());
		
			utilities.submitArticle(ePass, headline, sub_headline, 
									article_date, section, body, issue);
		} catch(Exception ex) {
			System.err.println("Fatal error...");
			System.exit(0);
		}
	}
	/**
	 * tests updateSection in the utilities class
	 * @author oconnecp
	 */
	static void callUpdateSection(){
		utilities.updateSection(1000, 3);
		utilities.updateRank(1000, 5);
		utilities.updateStatus(1000, 2);
	}
	
	/**
	 * Allows users to edit and update articles
	 * Presents the user with prompts for editing article information, then
	 * calls the appropriate Utilities method with the appropriate arguments.
	 * 
	 * @author Travis Towne
	 */
	static void editArticle() {
		ResultSet rset = utilities.getUpdateList();
		int index = 0;
		ArrayList<Integer> id = new ArrayList<Integer>();
		
		System.out.print("ePass: ");
		String ePass = in.nextLine();
		
		System.out.print("Enter the number corresponding to the article you would like to update.\n" +
					 	 "   -----------The Article's----------- --------The Author's--------\n" +
					 	 "   -------------Headline-------------- --First-Name-- --Last-Name--\n");
		try {
			while(rset.next()) {
				index++;
				id.add(rset.getInt(1));
				System.out.printf("%2s)%-35s %-14s %-13s\n", index, 
								  rset.getClob(2).getSubString(1l, (int)rset.getClob(2).length()), 
								  rset.getString(3), rset.getString(4));
			}
			index = in.nextInt();
			in.nextLine();
			
			System.out.print("Enter the number corresponding to what you want to edit.\n" +
						 	 "----Edit-Menu----\n" +
						 	 "1)Headline\n" +
						 	 "2)Sub_Headline\n" +
						 	 "3)Body\n" +
						 	 "4)Section\n" +
						 	 "5)Rank\n" +
						 	 "6)Status\n" +
						 	 "---->");
			int edit = in.nextInt();
			in.nextLine();
			
			utilities.updateArticle(ePass, id.get(index - 1), edit);
		} catch(Exception e) {
			System.err.println("Fatal Error...");
			System.exit(0);
		}
	}

	/**
	 * Prompts user for user for an ePass, a first, middle, and last name, and a role
	 * and then calls the Utilities.newUser() with the values provided
	 * @author oconnecp
	 */
	static void createUser(){
		String ePass, fName, mName, lName, stringRole;
		//byte role;
		
		System.out.print("ePass: ");
		ePass = in.nextLine();
		
		System.out.print("First name: ");
		fName = in.nextLine();
		
		System.out.print("Middle name: ");
		mName = in.nextLine();
		
		System.out.print("Last name: ");
		lName = in.nextLine();
		
		System.out.println("Choose from the following roles:\n" +
				"1 : Writer\n2 : Editor\n3 : Editor in Chief\n4 : Webmaster");
		
		
		System.out.print("Role: ");
		stringRole = in.nextLine();
		//role = Byte.parseByte(stringRole.trim());
		
		utilities.newUser(ePass, fName, mName, lName, stringRole);
	}
	
	/**
	 * Prompts user for section, article date, headline key, and issue date,
	 * calls Utilities.searchArchive(), then prints out the ID numbers and
	 * headlines of the result set.  Values entered as "&lt;null&gt;" will be
	 * interpreted into null values.
	 * @author Fredrik
	 */
	static void searchArchive() {
		int    section = -1;
		Date   articleDate;
		String headlineKey;
		Date   issue;
				
		String articleDateString;
		String issueString;
			
		System.out.print("Section # (-1 for any section): ");
		try {
			section = Integer.parseInt(in.nextLine());
		} catch(NumberFormatException e) {
			System.out.println("Not an integer. -1 will be used.");
		}
		
		System.out.print("Article date (YYYY-MM-DD, \"<null>\" for any date): ");
		articleDateString = in.nextLine();
		if (articleDateString.equals("<null>"))
			articleDate = null;
		else {
			try {
				articleDate = Date.valueOf(articleDateString);
			} catch (IllegalArgumentException e) {
				System.out.println("Malformed date.  Using <null>.");
				articleDate = null;
			}
		}
		
		System.out.print("Headline search key (\"<null>\" for none): ");
		headlineKey = in.nextLine();
		if (headlineKey.equals("<null>"))
			headlineKey = null;
		
		System.out.print("Issue date (YYYY-MM-DD, \"<null>\" for any date): ");
		issueString = in.nextLine();
		if (issueString.equals("<null>"))
			issue = null;
		else {
			try {
				issue = Date.valueOf(issueString);
			} catch (IllegalArgumentException e) {
				System.out.println("Malformed date.  Using <null>.");
				issue = null;
			}
		}
		
		try {
			ResultSet results =
				utilities.searchArchive(section, articleDate, headlineKey, issue);

			System.out.println("id\theadline");
			while (results.next()) {
				System.out.println(results.getString(1)+"\t"+
					results.getClob(2).getSubString(1l,
						(int)results.getClob(2).length()));
			}
		} catch (SQLException e) {
			System.out.println(e);
		}
	}
	
	/**
	 * Prompts user for a photo description, credit, large picture file path,
	 * small picture file path and article ID, and calls
	 * Utilities.insertPicture() with the appropriate arguments.
	 * @author Fredrik
	 * @author Chris
	 * @author Brad
	 */
	static void addNewPicture(){
		int    article;
		String alt;
		String credit;
		
		System.out.print("Description text: ");
		alt = in.nextLine();
		
		System.out.print("Photo credit: ");
		credit = in.nextLine();
		
		System.out.print("Large picture file path: ");
		String small = in.nextLine();
		
		File smallFile = new File(small);
		
		FileInputStream fstreams;
		BufferedInputStream smallStream = null;
		fstreams = null;
		try {
			fstreams = new FileInputStream(smallFile);
			smallStream = new BufferedInputStream(fstreams);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		System.out.print("Large picture file path: ");
		String large = in.nextLine();
		
		File largeFile = new File(large);
		FileInputStream fstreaml;
		BufferedInputStream largeStream = null;
		fstreaml = null;
		try {
			fstreaml = new FileInputStream(largeFile);
			largeStream = new BufferedInputStream(fstreaml);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		 
		System.out.print("Article ID #: ");
		article = Integer.parseInt(in.nextLine());
		
		try {
			utilities.insertPicture(article,alt,credit,smallStream,largeStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Prompts user for a picture ID and calls Utilities.deletePicture() with
	 * the provided ID as the argument.
	 * @author Brad
	 */
	static void deletePicture(){
		System.out.print("Picture to delete: ");
		String picID = in.nextLine();
		try {
			utilities.deletePicture(Integer.parseInt(picID));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
